<?php
namespace app\admin\controller;

use app\common\model\AdminAccessModel;
use app\common\model\AdminModel;
use app\common\model\DeptModel;
use app\common\model\SiteModel;
use think\Controller;
use think\facade\Session;

class PublicController extends Controller
{

    /**
     * 初始化方法
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 用户登录
     * @return mixed
     */
    public function login(){
        //重置所有登录信息
        Session::delete('session_key');
        Session::delete('platform');
        Session::delete('site');
        $adminModel = new AdminModel();
        if($this->request->isAjax()){
            try{
                $account = $this->request->param('account');
                $password = $this->request->param('password');
                $loginInfo = $adminModel->login($account,$password);
                $url = !empty($loginInfo['sites']) ? url('Public/select') : url('Index/index');
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功！',$url,$loginInfo);
        }
        return $this->fetch();
    }

    /**
     * 选择店铺
     */
    public function select(){
        $sessionKey = Session::get('session_key');
        if($sessionKey!='site'){
            return redirect('Public/login');
        }
        $loginInfo = Session::get($sessionKey);
        if(empty($loginInfo)){
            return redirect('Public/login');
        }
        if($this->request->isAjax()){
            try{
                $siteId = $this->request->param('site_id/d');
                $tradeId = SiteModel::where('id',$siteId)->value('trade_id');
                $access = AdminAccessModel::where('site_id','=',$siteId)
                                           ->where('admin_id',$loginInfo['id'])
                                           ->find();
                if(empty($access['group_id'])) exception('您在该站点未获得授权,请联系管理员为您开通！');
                unset($loginInfo['sites']);
                $loginInfo['site_id'] = $siteId;
                $loginInfo['dept_id'] = $access['dept_id'];
                $loginInfo['group_id'] = $access['group_id'];
                $loginInfo['trade_id'] = $tradeId;
                Session::set($sessionKey,$loginInfo);
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功！',url('Index/index'));
        }
        if(isset($loginInfo['site_id']) && isset($loginInfo['group_id'])){
            return redirect('Index/index'); //直接登录
        }else{
            $sites = $loginInfo['sites'];
            $siteIds = array_column($sites,'site_id');
            $siteList = SiteModel::where('id','in',$siteIds)->select();
            $this->assign('loginInfo',$loginInfo);
            $this->assign('sites',$siteList);
            return $this->fetch();
        }
    }

}
